package com.athl.netty.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author hl
 * @Data 2020/9/3
 */
public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int readCount = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送10条数据
        for (int i = 0; i < 10; i++) {
            String msg = "你好,我是你巴巴";
            int length = msg.getBytes(CharsetUtil.UTF_8).length;
            // 创建MessageProtocol
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setContent(msg.getBytes(CharsetUtil.UTF_8));
            messageProtocol.setLen(length);
            ctx.writeAndFlush(messageProtocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        byte[] content = msg.getContent();
        int len = msg.getLen();
        System.out.println("server发送 =" + new String(content, CharsetUtil.UTF_8));
        System.out.println("server发送 的 len =" + len);
        System.out.println("readCount = " + (++this.readCount));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("client 出现了异常 =" + cause.getMessage());
        ctx.close();
    }


}
